package model;

import com.sampullara.poker.Board;
import com.sampullara.poker.Card;
import com.sampullara.poker.HandRank;
import java.util.List;
import java.util.ArrayList;
import javax.servlet.http.HttpSession;

public class Player {
	
    private String name;
    private ArrayList<Card> cards;
    private String sessionID;
    private int currentBet;
    boolean folded;

    public Player(String name) {
        this.name = name;
        cards = new ArrayList<Card>(2);
        currentBet = 0;
        folded = false;
    }

    public void giveCard(Card card) {
        cards.add(card);
    }

    public String getName() {
        return name;
    }
    
    public boolean getFolded() {
    	return folded;
    }
    
    public void setFolded(boolean folded) {
    	this.folded = folded;
    }
    
    public int getCurrentBet() {
    	return currentBet;
    }
    
    public void setCurrentBet(int bet) {
    	currentBet = bet;
    }

    public void setSession(String sessionID){
        this.sessionID = sessionID;
    }

    public String getSession(){
        return sessionID;
    }

    public int getChips() {
    	int chips = new PlayerDao().getChips(name);
        return chips;
    }

    public void setChips(int chips) {
    	new PlayerDao().setChips(name, chips);
    }

    public ArrayList<Card> getCards() {
        return cards;
    }

    public void resetCards() {
        cards.clear();
    }
    
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        for (Card card : cards) {
            sb.append(card.toString());
        }
        return sb.toString();
    }

    public HandRank getHandRank(Board board) {
        // Create a new set of cards with all the cards in it sorted
        final List<Card> boardCards = board.getCards();
        List<Card> hand = new ArrayList<Card>(boardCards.size() + cards.size());
        addSorted(cards, hand);
        addSorted(boardCards, hand);

        // Look for hands
        return new HandRank(hand);
    }

    private void addSorted(List<Card> cards, List<Card> hand) {
        OUTER:
        for (Card card : cards) {
            for (int i = 0; i < hand.size(); i++) {
                if (hand.get(i).compareTo(card) < 0) {
                    hand.add(i, card);
                    continue OUTER;
                }
            }
            hand.add(card);
        }
    }
}
